<template>
  <a-spin :spinning="loading" wrapper-class-name="w-full h-full">
    <div v-if="!!iframe" class="w-full h-full">
      <a-spin :tip="iframe + '正在加载...'" wrapper-class-name="w-full h-full" :spinning="iframeLoading">
        <iframe id="iframe" :src="iframe" frameborder="0" width="100%" height="100%"></iframe>
      </a-spin>
    </div>
    <template v-else>
      <SearchContainer ref="searchContainerRef" show-export :export-disabled="!!dataSource.length" @search="getDate" @reset="onReset" @export="onExport">
        <DynamicForm v-if="formConfig" v-model:value="formState" :form-config="formConfig" />
      </SearchContainer>
      <a-card class="mt-2">
        <BaseTable
          v-if="tableColumns.length > 0"
          fill
          :columns="tableColumns"
          :extra-height="getExtraHeight()"
          :pagination="isPage ? { total: dataSource.length, current: page.current, pageSize: page.pageSize } : false"
          :scroll="{ x: tableWidth }"
          :data-source="dataSource"
          @change="onPageChange"
        >
          <template v-if="isSum" #summary>
            <a-table-summary fixed>
              <a-table-summary-row>
                <a-table-summary-cell v-if="dataSource.length === 0"> 合计 </a-table-summary-cell>
                <template v-else>
                  <a-table-summary-cell v-for="(column, index) in tableColumns" :key="column.dataIndex">
                    <div v-if="column.count === 1" class="text-right">{{ formatAmount(summaryData[column.dataIndex]) }}</div>
                    <template v-if="index === 0">合计</template>
                  </a-table-summary-cell>
                </template>
              </a-table-summary-row>
            </a-table-summary>
          </template>
        </BaseTable>
      </a-card>
    </template>
  </a-spin>
</template>

<script setup>
import { nextTick, onMounted, ref, watchEffect } from 'vue'
import { message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import SearchContainer from '@/components/SearchContainer'
import BaseTable from '@/components/BaseTable'
import DynamicForm from '@/components/DynamicForm'
import { post, http } from '@/utils/request'
import useAppStore from '@/store/app'
import useUserStore from '@/store/user'
import { formatAmount, formatDate } from '@/utils/format.js'
import cofirmModal from '@/utils/confirm.js'

const route = useRoute()
const router = useRouter()
const loading = ref(true)
const iframeLoading = ref(true)
const isPage = ref(false)
const tableWidth = ref('100%')
const page = ref({
  current: 1,
  pageSize: 20
})
const reportName = ref('')
const formState = ref({})
const searchContainerRef = ref(null)
const tableColumns = ref([])
const iframe = ref(null)
const formConfig = ref([])
const dataSource = ref([])
const appStore = useAppStore()
const { empId } = useUserStore()
const isSum = ref(false)
const getConfig = async () => {
  loading.value = true
  isSum.value = false
  dataSource.value = []
  formConfig.value = []
  formState.value = {}
  tableColumns.value = []
  const { code, data, msg } = await post('/ufs/report/getModel', { reportId: route.query.id })
  loading.value = false
  if (code !== 0) return message.error(msg || '查询失败')
  reportName.value = data.reportName
  isPage.value = data.isPage === '1'
  if (data.reportType === 'sql' || data.reportType === 'server') {
    iframe.value = null
    formConfig.value = data.reportParameterList?.map((list) => {
      const { parameterType, parameterTitle, parameterName, operator, defaultValue } = list
      return {
        operator: operator,
        type: parameterType,
        label: parameterTitle,
        value: defaultValue,
        key: parameterName,
        ...list
      }
    })
    tableColumns.value = data.reportTableColumnList.filter((item) => {
      item.width = isNaN(item.width) ? item.width : Number(item.width) || ''
      if (item.format) {
        item.customRender = (record) => formatValue(record)
      }
      if (item.sorter) {
        item.sorter = (a, b) => sorterFunc(a[item.dataIndex], b[item.dataIndex])
      }
      if (item.count === 1 && !isSum.value) {
        isSum.value = true
      }
      item.ellipsis = !!item.ellipsis
      return !item.isHide
    })
    tableWidth.value = tableColumns.value.reduce((total, item) => {
      const width = +item.width
      const minWidth = Number.isInteger(width) ? width : 100
      return total + minWidth
    }, 0)
    searchContainerRef.value?.calcHeight()
  } else {
    iframe.value = data.url
    iframeLoad()
  }
}
const sorterFunc = (a, b) => {
  if (typeof a === 'string') {
    return a.localeCompare(b)
  } else if (typeof a === 'number') {
    return a - b
  }
}
const formatValue = ({ text, column }) => {
  switch (column.format) {
    case '两位小数':
      return formatAmount(text, 2, false)
    case '三位小数':
      return formatAmount(text, 3, false)
    case '五位小数':
      return formatAmount(text, 5, false)
    case '长日期':
      return formatDate(text, 'YYYY-MM-DD HH:mm:ss')
    case '短日期':
      return formatDate(text, 'YYYY-MM-DD')
    default:
      return text
  }
}
watchEffect(() => {
  route.query.id && getConfig()
})

const getDate = async () => {
  const conditions = formConfig.value.map((config) => {
    const value = formState.value[config.key]
    return {
      operator: config.operator,
      parameterName: config.key,
      parameterType: config.type,
      parameterValue: Array.isArray(value) ? value.join(',') : value
    }
  })
  loading.value = true
  const { code, data, msg } = await post('/ufs/report/getReportData', { reportId: route.query.id, conditions })
  loading.value = false
  if (code !== 0) return message.error(msg || '查询失败')
  if (data.length > 1000) {
    const isConfirm = await cofirmModal({ title: '提示', content: '数据量超过1000条，是否开启分页？' })
    if (isConfirm) {
      isPage.value = true
    }
  }
  dataSource.value = data
  getSummary()
}

const onReset = () => {
  for (const key in formState.value) {
    if (!Array.isArray(formState.value[key])) {
      formState.value[key] = undefined
    }
  }
}

const getTimeName = (arr) => {
  arr.forEach((obj) => {
    if (obj.parameterValue && obj.parameterValue.includes(',')) {
      let dateRange = obj.parameterValue.split(',')
      dateRange = dateRange.map((date) => {
        return date.replace(/-/g, '')
      })
      obj.parameterValue = dateRange.join('-')
    } else {
      obj.parameterValue = obj.parameterValue?.replace(/-/g, '')
    }
  })
  const arrTimeName = arr.filter((i) => i.parameterValue)
  return arrTimeName?.[1] ? arrTimeName[0].parameterValue + '-' + arrTimeName[1].parameterValue : arrTimeName[0]?.parameterValue || ''
  // return arr.filter((i) => i.parameterValue)[0]?.parameterValue
}

const onExport = async () => {
  const conditions = formConfig.value.map((config) => {
    const value = formState.value[config.key]
    return {
      operator: config.operator,
      parameterName: config.key,
      parameterType: config.type,
      parameterValue: Array.isArray(value) ? value.join(',') : value
    }
  })
  http
    .post('/ufs/report/exportdata', { reportId: route.query.id, conditions }, { responseType: 'blob' })
    .then((res) => {
      const href = URL.createObjectURL(res.data)
      const element = document.createElement('a')
      element.download = reportName.value + getTimeName(conditions) || '' + '.xlsx'
      element.href = href
      element.click()
      message.success('导出成功')
    })
    .catch(() => {
      message.error('导出失败，请稍后重试！')
    })
}
const getMenuList = async () => {
  const { code, data = [] } = await post('/ufs/report/getReportList', {
    applicationId: '1703963394688258049',
    applicationName: 'Fudansoft iMedicalCare',
    pageNum: 1,
    pageSize: 1000
  })
  if (code !== 0) return message.error('获取报表路由失败')
  const filterData = data.filter((item) => {
    return reportAuthority.value.includes(item.id)
  })
  appStore.reportRoute = groupByKey(filterData)
  if (!route.query.id && appStore.reportRoute[0]?.children[0]?.id) {
    const categoryId = appStore.reportRoute[0].children[0].categoryId
    router.push(`/report?categoryId=${categoryId}&id=${appStore.reportRoute[0].children[0].id}`)
  }
}
const groupByKey = (reports) => {
  const groupedReports = {}
  reports.forEach((report) => {
    const categoryId = report.categoryId
    const categoryName = report.categoryName
    if (!groupedReports[categoryId]) {
      groupedReports[categoryId] = {
        path: '/report?categoryId=' + categoryId,
        label: categoryName,
        categoryId,
        children: []
      }
    }
    groupedReports[categoryId].children.push({
      id: report.id,
      categoryId: report.categoryId,
      path: `/report?categoryId=${categoryId}&id=${report.id}`,
      label: report.reportName,
      meta: report
    })
  })
  return Object.values(groupedReports)
}
const summaryData = ref({})
const getSummary = () => {
  const summary = {}
  const sumColumns = tableColumns.value.filter((item) => item.count === 1).map((item) => item.dataIndex)
  dataSource.value.forEach((data) => {
    sumColumns.forEach((column) => {
      summary[column] = (+data[column] || 0) + (+summary[column] || 0)
    })
  })
  summaryData.value = summary
}
const reportAuthority = ref([])
const getReportAuthority = async () => {
  const { data, code, msg } = await post('/operation/opex/getSystemDataReportFormPermissionsList', {
    permissonType: 3,
    empId: empId
  })
  if (code !== 0) return message.error(msg)
  reportAuthority.value = data.map((item) => item.permissonCode)
  getMenuList()
}
onMounted(async () => {
  appStore.CURRENT_ROUTE_NAME = '报表中心'
  getReportAuthority()
})
onBeforeUnmount(() => {
  empId && router.push({ path: '/' })
})
const onPageChange = ({ current, pageSize }) => {
  page.value.current = current
  page.value.pageSize = pageSize
}
const getExtraHeight = () => {
  let height = 0
  if (isSum.value) {
    height = height + 48
  }
  // if (isPage.value) {
  //   height = height + 48
  // }
  return height
}
// 判断iframe是否加载完成
const iframeLoad = () => {
  nextTick(() => {
    const iframe = document.querySelector('#iframe')
    // 处理兼容行问题 兼容IE
    if (iframe.attachEvent) {
      iframe.attachEvent('onload', function () {
        // iframe加载完毕以后执行操作
        iframeLoading.value = false
      })
    } else {
      iframe.onload = function () {
        // iframe加载完毕以后执行操作
        iframeLoading.value = false
      }
    }
  })
}
</script>
<style lang="less" scoped>
:deep(.ant-spin-container) {
  width: 100%;
  height: 100%;
}
:deep(.ant-table-thead) > tr > th {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
